<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  getPerformerById,
  getPerformersByPage,
  updatePerformers,
  createPerformers,
  deletePerformers
} from '@/api/perfomers'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Delete } from '@element-plus/icons-vue'

// 状态数据
let tableData = ref([])
let loading = ref(false)
let total = ref(0)
let dialogVisible = ref(false)

const formRef = ref()

// 表单数据
const form = reactive({
  performersId: '',
  avatarUrl: '',
  avataRaw: '',
  name: '',
  introduction: '',
  pictureUrl: '',
  pictureRaw: ''
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入演出者姓名', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入简介', trigger: 'blur' }]
}

const isEdit = ref(false)
// 查看/修改方法
const handleChange = async (row) => {
  isEdit.value = true
  dialogVisible.value = true
  // 将行数据复制到表单
  Object.assign(form, row)
  console.log(form)
}

const submitForm = async () => {
  try {
    loading.value = true

    if (isEdit.value) {
      await updatePerformers(form)
    } else {
      await createPerformers(form)
    }

    ElMessage({
      type: 'success',
      message: isEdit.value ? '更新成功' : '创建成功'
    })
    dialogVisible.value = false
    pageQuery() // 重新加载数据
  } catch (error) {
    console.error('Submit form error:', error)
    ElMessage({
      type: 'error',
      message: '操作失败：' + error.message
    })
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row) => {
  ElMessageBox.confirm('确认要删除该演出吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true
        await deletePerformers(row.performersId)
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        pageQuery() // 重新加载数据
      } catch (error) {
        console.error('Delete error:', error)
        ElMessage({
          type: 'error',
          message: '删除失败：' + error.message
        })
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

const createPerform = () => {
  dialogVisible.value = true
  isEdit.value = false
  // 将form置空
  Object.assign(form, {
    performersId: '',
    avatarUrl: '',
    avataRaw: '',
    name: '',
    introduction: '',
    pictureUrl: '',
    pictureRaw: ''
  })
}

// 搜索和分页参数，将 dateRange 拆分为 startDate 和 endDate
let queryParams = reactive({
  name: ''
})

let pageNum = ref(1)
let pageSize = ref(10)
// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val

  pageQuery()
}

const handleCurrentChange = (val) => {
  pageNum.value = val

  pageQuery()
}

const pageQuery = async () => {
  const res = await getPerformersByPage(pageNum.value, pageSize.value)
  console.log(res)
  tableData.value = res.data.data
  total.value = res.data.total
}

// const submitForm = async (formEl) => {
//   if (!formEl) return
//   await formEl.validate(async (valid) => {
//     if (valid) {
//       try {
//         loading.value = true
//         const submitData = {
//           name: performForm.name,
//           typeId: performForm.typeId, // 因为checkbox-group返回数组，我们取第一个值
//           venuesId: performForm.venueId,
//           images: performForm.images || 'safa',
//           openTime: performForm.openTime.toISOString(),
//           performTime: performForm.performTime.toISOString(),
//           title: performForm.name, // 用name作为title
//           performersIdList: [1], // 如果需要可以添加演出者
//           score: Math.floor(Math.random() * 30) + 70 // 模拟评分70-100
//         }

//         console.log(submitData)

//         if (isEdit.value) {
//           console.log({
//             ...submitData,
//             performId: performForm.performId
//           })
//           await updateperform({
//             ...submitData,
//             performId: performForm.performId
//           })
//         } else {
//           await createperform(submitData)
//         }

//         ElMessage({
//           type: 'success',
//           message: isEdit.value ? '更新成功' : '创建成功'
//         })
//         dialogVisible.value = false
//         fetchPerforms() // 重新加载数据
//       } catch (error) {
//         console.error('Submit form error:', error)
//         ElMessage({
//           type: 'error',
//           message: '操作失败：' + error.message
//         })
//       } finally {
//         loading.value = false
//       }
//     }
//   })
// }
// 修改状态选项
const statusOptions = [
  { value: 1, label: '未演出', type: 'success' },
  { value: 2, label: '已演出', type: 'warning' }
]

// 修改状态选项
const CityOptions = [
  { value: 1, label: '武汉' },
  { value: 2, label: '南昌' },
  { value: 3, label: '北京' },
  { value: 4, label: '保山' },
  { value: 5, label: '长春' },
  { value: 6, label: '长沙' },
  { value: 7, label: '常德' },
  { value: 8, label: '重庆' },
  { value: 9, label: '成都' },
  { value: 10, label: '大庆' }
]

// 搜索和重置处理
const handleSearch = async () => {
  pageNum.value = 1
  pageSize.value = 1

  const res = await getPerformerById(queryParams.name)
  tableData.value = res.data
}
const handleReset = () => {
  queryParams.name = ''
  queryParams.minFan = ''
  queryParams.maxFan = ''

  pageNum.value = 1
  pageSize.value = 10

  pageQuery()
}

let performerForm = reactive({
  name: null,
  typeId: null,
  venuesId: null,
  images: '',
  want: 0,
  openTime: '',
  performTime: '',
  location: null,
  count: null,
  venueName: null
})

onMounted(() => {
  pageQuery()
})
</script>

<template>
  <div class="order-list">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form
        :inline="true"
        :model="queryParams"
        class="flex items-center flex-wrap gap-4"
      >
        <el-form-item label="演出者:">
          <el-input v-model="queryParams.name" />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" :icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
        <el-form-item style="position: absolute; right: 0">
          <el-space>
            <el-button type="primary" :icon="Search" @click="createPerform">
              创建
            </el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card mt-4" shadow="hover">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: auto"
        :header-cell-style="{ backgroundColor: '#f5f7fa' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="performersId"
          label="演员编号"
          width="120"
          align="center"
        />
        <el-table-column label="头像" width="140" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.avatarUrl"
              :src="row.avatarUrl"
              fit="cover"
              class="perfomer-image"
            />
            <el-icon v-else><Picture /></el-icon>
          </template>
        </el-table-column>
        <el-table-column label="演唱会海报" width="140" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.pictureUrl"
              :src="row.pictureUrl"
              fit="cover"
              class="perfomer-image"
            />
            <el-icon v-else><Picture /></el-icon>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="演出者"
          width="120"
          align="center"
        />
        <el-table-column
          prop="introduction"
          label="简介"
          width="300"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="followers"
          label="粉丝"
          width="120"
          align="center"
        />
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="primary"
                link
                :icon="View"
                @click="handleChange(row)"
              >
                修改
              </el-button>
              <el-button
                type="danger"
                link
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination mt-4">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 修改弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '修改演出者信息' : '创建演出者信息'"
      width="600px"
      after-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="performer-form"
      >
        <el-form-item label="演出者" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="简介" prop="introduction">
          <el-input
            v-model="form.introduction"
            type="textarea"
            :rows="3"
            placeholder="请输入演出者简介"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm()">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
/*解决ie11下el-table出现空白问题*/
:deep(.el-table__header) {
  width: 100% !important;
}
:deep(.el-table__body) {
  width: 100% !important;
}

.order-list {
  padding: 40px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-card,
.table-card {
  background-color: #ffffff;
  border-radius: 8px;
  position: relative;
}

.table-card {
  margin-top: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.order-detail {
  padding: 20px;
}

.total-amount {
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
}

.amount {
  color: #f56c6c;
  font-size: 20px;
  margin-left: 8px;
  font-weight: bold;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.status-select) {
  width: 160px;
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
}

:deep(.el-tag) {
  min-width: 60px;
  text-align: center;
}

.mx-2 {
  width: 100px;
}

.perfomer-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.performer-form {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  gap: 20px;

  & > .el-form-item {
    width: 90%;
  }

  .avatar-uploader,
  .poster-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .avatar,
    .poster {
      width: 120px;
      height: 120px;
      display: block;
    }

    .avatar-uploader-icon,
    .poster-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      text-align: center;
      line-height: 120px;
    }
  }
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;

  .el-button {
    margin-left: 12px;
  }
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #606266;
  background-color: #f5f7fa;
}
</style>
